Imports System.IO
Imports System.Data.SqlClient
Imports System.Web.Mail
Imports NENAData.NENAMember
Imports Secure.Functions

Public Class ProvincialEmailMembers
    Inherits System.Web.UI.Page

#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub
    Protected WithEvents Label1 As System.Web.UI.WebControls.Label
    Protected WithEvents Label2 As System.Web.UI.WebControls.Label
    Protected WithEvents btnSend As System.Web.UI.WebControls.Button
    Protected WithEvents btnCancel As System.Web.UI.WebControls.Button
    Protected WithEvents ftbMessage As FreeTextBoxControls.FreeTextBox
    Protected WithEvents txtFrom As System.Web.UI.WebControls.TextBox
    Protected WithEvents Label3 As System.Web.UI.WebControls.Label
    Protected WithEvents txtSubject As System.Web.UI.WebControls.TextBox
    Protected WithEvents RequiredFieldValidator1 As System.Web.UI.WebControls.RequiredFieldValidator
    Protected WithEvents RequiredFieldValidator2 As System.Web.UI.WebControls.RequiredFieldValidator
    Protected WithEvents RequiredFieldValidator3 As System.Web.UI.WebControls.RequiredFieldValidator
    Protected WithEvents ValidationSummary1 As System.Web.UI.WebControls.ValidationSummary
    Protected WithEvents txtAffiliate As System.Web.UI.WebControls.TextBox
    Protected WithEvents ddlEmailMembers As System.Web.UI.WebControls.DropDownList
    Protected WithEvents Label4 As System.Web.UI.WebControls.Label
    Protected WithEvents ofdAttachment1 As System.Web.UI.HtmlControls.HtmlInputFile

    'NOTE: The following placeholder declaration is required by the Web Form Designer.
    'Do not delete or move it.
    Private designerPlaceholderDeclaration As System.Object

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub

#End Region
    Dim strAffiliateID As String
    Protected strMessageBody, strSentTo As String

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        strAffiliateID = Request.QueryString("AffiliateID")
        'verify user is accessing an affiliate they have rights to
        VerifyAffiliate(strAffiliateID)

        btnCancel.CausesValidation = False

        If Not IsPostBack Then
            BindEmailDDL()
        End If
    End Sub

    Private Sub BindEmailDDL()
        ddlEmailMembers.DataSource = Create_Email_Array()
        ddlEmailMembers.DataTextField = "description"
        ddlEmailMembers.DataValueField = "id"
        ddlEmailMembers.DataBind()

    End Sub

    Private Sub SendUserEmail()
        'Response.Write(strHTMLFormatted)
        Dim objMail As New MailMessage

        'bad words
        'your, payment, questions, address, email, city

        Dim attach1 As String = ""
        Dim strFileName As String = ""
        Dim strUploadTime, strOnlyFileName, strUserAttachmentMessage As String
        Dim strSendFileName As String

        If ofdAttachment1.PostedFile.FileName <> "" Then

            'Get a reference to PostedFile object
            Dim ulFile As HttpPostedFile = ofdAttachment1.PostedFile
            'Get size of the file
            Dim nFileLen As Integer = ulFile.ContentLength
            'Make sure the size of the file is > 0
            If nFileLen > 0 Then
                'Get the file name
                strFileName = Path.GetFileName(ofdAttachment1.PostedFile.FileName)
                'Preced the file name with "attachments/" so 
                'the file is saved to our attachments directory
                'strFileName = "Attachments/" + strFileName
                strUploadTime = "-" & Now.Day & Now.Month & Now.Year & "." & Now.Hour & Now.Minute
                strOnlyFileName = Left(strFileName, strFileName.Length - 4) & strUploadTime & Right(strFileName, 4)
                strUserAttachmentMessage = strOnlyFileName
                strSendFileName = "Attachments/" & strOnlyFileName
                'Save the file on the server
                ofdAttachment1.PostedFile.SaveAs(Server.MapPath(strSendFileName))
                'Create the email attachment with the uploaded file
                Dim attach As MailAttachment = New MailAttachment(Server.MapPath(strSendFileName))
                'Attach the newly created email attachment
                objMail.Attachments.Add(attach)
                'Store filename so we can delete it later
                attach1 = strFileName
            End If
        End If

        If strOnlyFileName <> "" Then
            strMessageBody = ftbMessage.Text & "<br /><br /> File Attached: " & strOnlyFileName
        Else
            strMessageBody = ftbMessage.Text
        End If

        Dim strEmailAddresses As String

        Dim oNENAMember As New NENAMember
        strEmailAddresses = oNENAMember.GetEmailAddresses(MemberStatus.Status.Paid, strAffiliateID)

        objMail.From = txtFrom.Text
        objMail.To = txtFrom.Text
        objMail.Bcc = "gary.pronych@accesscomm.ca;" & "jerry.bell@rqhealth.ca;" & strEmailAddresses
        objMail.Subject = SqlReplaceText(txtSubject.Text)
        objMail.Body = strMessageBody
        objMail.BodyFormat = MailFormat.Html
        SmtpMail.SmtpServer = "localhost"

        SmtpMail.Send(objMail)
        SaveEmailSentToDB()
        'Response.Write("email will be sent to" & strEmailAddresses)
        'Response.Write(GetMemberEmailAddresses)

    End Sub


#Region "Email Array"
    Private Function Create_Email_Array() As DataTable
        Dim dt As New DataTable
        Dim dr As DataRow

        dt.Columns.Add(New DataColumn("ID", GetType(String)))
        dt.Columns.Add(New DataColumn("Description", GetType(String)))

        dr = dt.NewRow()
        dr(0) = "0"
        dr(1) = "All Members"
        dt.Rows.Add(dr)
        dr = dt.NewRow()
        dr(0) = "1"
        dr(1) = "ENGBC"
        dt.Rows.Add(dr)
        dr = dt.NewRow()
        dr(0) = "2"
        dr(1) = "ENIG"
        dt.Rows.Add(dr)
        dr = dt.NewRow()
        dr(0) = "3"
        dr(1) = "SENG"
        dt.Rows.Add(dr)
        dr = dt.NewRow()
        dr(0) = "4"
        dr(1) = "EDNA"
        dt.Rows.Add(dr)
        dr = dt.NewRow()
        dr(0) = "5"
        dr(1) = "ENAO"
        dt.Rows.Add(dr)
        dr = dt.NewRow()
        dr(0) = "6"
        dr(1) = "NBENA"
        dt.Rows.Add(dr)
        dr = dt.NewRow()
        dr(0) = "7"
        dr(1) = "NSENA"
        dt.Rows.Add(dr)
        dr = dt.NewRow()
        dr(0) = "8"
        dr(1) = "PEIENA"
        dt.Rows.Add(dr)
        dr = dt.NewRow()
        dr(0) = "9"
        dr(1) = "NLENA"
        dt.Rows.Add(dr)
        dr = dt.NewRow()
        dr(0) = "10"
        dr(1) = "International"
        dt.Rows.Add(dr)
        dr = dt.NewRow()
        dr(0) = "11"
        dr(1) = "Independant"
        dt.Rows.Add(dr)

        Return dt
    End Function

#End Region

    Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click

        SendUserEmail()
        Response.Redirect("default.aspx")
        'Response.Write("email sent")

    End Sub

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click

        Response.Redirect("default.aspx")

    End Sub

    Private Sub SaveEmailSentToDB()
        Dim conPubs As SqlConnection
        Dim cmdSelect As SqlCommand
        Dim strSQL As String

        strSQL = "insert into EmailSent  " & _
            "(Message, SentUser, SentTo, SentFrom) " & _
            "values (@parMessage, @parSentUser, @parSentTo, @parSentFrom)"

        conPubs = New SqlConnection(ConfigurationManager.AppSettings.Item("SQLConnectionString"))
        cmdSelect = New SqlCommand(strSQL, conPubs)

        cmdSelect.Parameters.Add("@parMessage", SqlDbType.NVarChar).Value = strMessageBody
        cmdSelect.Parameters.Add("@parSentUser", SqlDbType.NVarChar).Value = User.Identity.Name.ToString()
        cmdSelect.Parameters.Add("@parSentTo", SqlDbType.NVarChar).Value = txtAffiliate.Text
        cmdSelect.Parameters.Add("@parSentFrom", SqlDbType.NVarChar).Value = txtFrom.Text

        conPubs.Open()
        cmdSelect.ExecuteNonQuery()
        conPubs.Close()

    End Sub


#Region " Verifying Affiliate ID "

    Public Sub VerifyAffiliate(ByVal strAffiliateID As String)
        Select Case strAffiliateID
            Case 1
                If User.IsInRole(ConfigurationManager.AppSettings.Item("RoleModerator")) Or _
                    User.IsInRole(ConfigurationManager.AppSettings.Item("RoleAdmin")) Or _
                    User.IsInRole(ConfigurationManager.AppSettings.Item("RoleBC")) Then
                    txtAffiliate.Text = ConfigurationManager.AppSettings.Item("RoleBC")
                Else
                    Response.Redirect("")
                End If
            Case 2
                If User.IsInRole(ConfigurationManager.AppSettings.Item("RoleModerator")) Or _
                    User.IsInRole(ConfigurationManager.AppSettings.Item("RoleAdmin")) Or _
                    User.IsInRole(ConfigurationManager.AppSettings.Item("RoleAB")) Then
                    txtAffiliate.Text = ConfigurationManager.AppSettings.Item("RoleAB")
                Else
                    Response.Redirect("")
                End If
            Case 3
                If User.IsInRole(ConfigurationManager.AppSettings.Item("RoleModerator")) Or _
                    User.IsInRole(ConfigurationManager.AppSettings.Item("RoleAdmin")) Or _
                    User.IsInRole(ConfigurationManager.AppSettings.Item("RoleSK")) Then
                    txtAffiliate.Text = ConfigurationManager.AppSettings.Item("RoleSK")
                Else
                    Response.Redirect("")
                End If
            Case 4
                If User.IsInRole(ConfigurationManager.AppSettings.Item("RoleModerator")) Or _
                    User.IsInRole(ConfigurationManager.AppSettings.Item("RoleAdmin")) Or _
                    User.IsInRole(ConfigurationManager.AppSettings.Item("RoleMB")) Then
                    txtAffiliate.Text = ConfigurationManager.AppSettings.Item("RoleMB")
                Else
                    Response.Redirect("")
                End If
            Case 5
                If User.IsInRole(ConfigurationManager.AppSettings.Item("RoleModerator")) Or _
                    User.IsInRole(ConfigurationManager.AppSettings.Item("RoleAdmin")) Or _
                    User.IsInRole(ConfigurationManager.AppSettings.Item("RoleONT")) Then
                    txtAffiliate.Text = ConfigurationManager.AppSettings.Item("RoleONT")
                Else
                    Response.Redirect("")
                End If
            Case 6
                If User.IsInRole(ConfigurationManager.AppSettings.Item("RoleModerator")) Or _
                    User.IsInRole(ConfigurationManager.AppSettings.Item("RoleAdmin")) Or _
                    User.IsInRole(ConfigurationManager.AppSettings.Item("RoleNB")) Then
                    txtAffiliate.Text = ConfigurationManager.AppSettings.Item("RoleNB")
                Else
                    Response.Redirect("")
                End If
            Case 7
                If User.IsInRole(ConfigurationManager.AppSettings.Item("RoleModerator")) Or _
                    User.IsInRole(ConfigurationManager.AppSettings.Item("RoleAdmin")) Or _
                    User.IsInRole(ConfigurationManager.AppSettings.Item("RoleNS")) Then
                    txtAffiliate.Text = ConfigurationManager.AppSettings.Item("RoleNS")
                Else
                    Response.Redirect("")
                End If
            Case 8
                If User.IsInRole(ConfigurationManager.AppSettings.Item("RoleModerator")) Or _
                    User.IsInRole(ConfigurationManager.AppSettings.Item("RoleAdmin")) Or _
                    User.IsInRole(ConfigurationManager.AppSettings.Item("RolePEI")) Then
                    txtAffiliate.Text = ConfigurationManager.AppSettings.Item("RolePEI")
                Else
                    Response.Redirect("")
                End If
            Case 9
                If User.IsInRole(ConfigurationManager.AppSettings.Item("RoleModerator")) Or _
                    User.IsInRole(ConfigurationManager.AppSettings.Item("RoleAdmin")) Or _
                    User.IsInRole(ConfigurationManager.AppSettings.Item("RoleNF")) Then
                    txtAffiliate.Text = ConfigurationManager.AppSettings.Item("RoleNF")
                Else
                    Response.Redirect("")
                End If
            Case 10
                If User.IsInRole(ConfigurationManager.AppSettings.Item("RoleModerator")) Or _
                    User.IsInRole(ConfigurationManager.AppSettings.Item("RoleAdmin")) Or _
                    User.IsInRole(ConfigurationManager.AppSettings.Item("RoleOTHER")) Then
                    txtAffiliate.Text = ConfigurationManager.AppSettings.Item("RoleOTHER")
                Else
                    Response.Redirect("")
                End If
        End Select
    End Sub
#End Region

    'Public Function GetMemberEmailAddresses() As String
    '    Dim strsql As String
    '    Dim sqlReaderTo As SqlDataReader
    '    Dim strarray As String = ""

    '    Dim objConn As SqlConnection = New SqlConnection(ConfigurationManager.AppSettings.Item("SQLConnectionString"))
    '    Dim cmdGetEmail As SqlCommand

    '    strsql = "SELECT emailaddress " & _
    '    "from Members " & _
    '    "where affiliate_id = " & strAffiliateID & _
    '    " and account_status = 3"

    '    cmdGetEmail = New SqlCommand(strsql, objConn)
    '    cmdGetEmail.CommandType = CommandType.Text
    '    objConn.Open()
    '    sqlReaderTo = cmdGetEmail.ExecuteReader(CommandBehavior.CloseConnection)

    '    While sqlReaderTo.Read()
    '        strarray += sqlReaderTo.GetString(0)
    '        strarray += "; "
    '    End While

    '    sqlReaderTo.Close()
    '    Return (strarray)
    '    'Return (strsql)
    '    'Response.Write(strsql)
    'End Function
End Class
